package com.raylu.day06;

import com.raylu.utils.ItemViewCountPerWindow;
import com.raylu.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Properties;

// 实时热门商品
// 每隔5分钟计算一次过去一小时的访问次数最多的三个商品
public class Example8RealTimeHotProduct1h1minStepTopN {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        Properties props = new Properties();
        props.setProperty("bootstrap.servers", "localhost:9092");
        props.setProperty("group.id", "consumer-group");
        props.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.setProperty("auto.offset.reset", "latest");

        SingleOutputStreamOperator<UserBehavior> source = env
                // userId,itemID,categoryId,type,ts
                // 543462,1715,1464116,pv,1511658000
                .addSource(new FlinkKafkaConsumer<String>(
                        "userbehavior-0701",
                        new SimpleStringSchema(),
                        props
                ))
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] arr = value.split(",");
                        return new UserBehavior(
                                arr[0], arr[1], arr[2], arr[3],
                                Long.parseLong(arr[4]) * 1000L
                        );
                    }
                })
                .filter(r -> r.type.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                );

        // 第一步 计算每个商品在每个窗口中的pv次数
        // select itemId, count(itemId) as count, window_end() as windowEnd from table group by itemId, window;
        SingleOutputStreamOperator<ItemViewCountPerWindow> itemViewCountPerWindowStream = source
                // 按照商品id进行逻辑分区
                .keyBy(r -> r.itemId)
                // 开窗口
                .window(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(5)))
                .aggregate(new CountAgg(), new WindowResult());

        // 对windowEnd对应的每个逻辑分区进行排序操作，按照count字段降序排列
        // select * from table partition by windowEnd order by count desc limit 3;
        SingleOutputStreamOperator<String> result = itemViewCountPerWindowStream
                // 每个逻辑分区：属于同一个窗口的不同itemId的ItemViewCountPerWIndow
                .keyBy(r -> r.windowEnd)
                .process(new TopN(3));

        result.print();

        env.execute();
    }

    public static class TopN extends KeyedProcessFunction<Long, ItemViewCountPerWindow, String> {
        private int n;

        public TopN(int n) {
            this.n = n;
        }

        private ListState<ItemViewCountPerWindow> listState;

        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            listState = getRuntimeContext().getListState(
                    new ListStateDescriptor<ItemViewCountPerWindow>("list-state", Types.POJO(ItemViewCountPerWindow.class))
            );
        }

        @Override
        public void processElement(ItemViewCountPerWindow value, Context ctx, Collector<String> out) throws Exception {
            // 每来一条数据，添加到列表状态变量中
            listState.add(value);

            // 当水位线高于windowEnd，就可以排序了
            // 只会注册一次排序定时器
            ctx.timerService().registerEventTimeTimer(value.windowEnd + 100L);
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            super.onTimer(timestamp, ctx, out);
            // 首先将列表状态变量中的数据放到ArrayList中
            ArrayList<ItemViewCountPerWindow> arrayList = new ArrayList<>();
            for (ItemViewCountPerWindow e : listState.get()) arrayList.add(e);

            // 对ArrayList排序
            arrayList.sort(new Comparator<ItemViewCountPerWindow>() {
                @Override
                public int compare(ItemViewCountPerWindow t1, ItemViewCountPerWindow t2) {
                    // 按照count降序排列
                    return t2.count.intValue() - t1.count.intValue();
                }
            });

            StringBuilder result = new StringBuilder();
            result.append("====================================================\n");
            result.append("窗口结束时间：" + new Timestamp(timestamp - 100L) + "\n");
            for (int i = 0; i < n; i++) {
                ItemViewCountPerWindow temp = arrayList.get(i);
                result.append("第" + (i + 1) + "名的商品ID：" + temp.itemId + "，浏览次数：" + temp.count + "\n");
            }
            result.append("====================================================\n");
            out.collect(result.toString());
        }
    }

    public static class CountAgg implements AggregateFunction<UserBehavior, Long, Long> {
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(UserBehavior value, Long accumulator) {
            return accumulator + 1L;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return null;
        }
    }

    public static class WindowResult extends ProcessWindowFunction<Long, ItemViewCountPerWindow, String, TimeWindow> {
        @Override
        public void process(String s, Context context, Iterable<Long> elements, Collector<ItemViewCountPerWindow> out) throws Exception {
            out.collect(new ItemViewCountPerWindow(
                    s,
                    elements.iterator().next(),
                    context.window().getStart(),
                    context.window().getEnd()
            ));
        }
    }
}
